package org.zero.onlinesubject.utils;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class SessionContext {
    // 会话关系映射
    private static Map<String, Session> sessionPool = new ConcurrentHashMap<>();
    private static Map<String, List<String>> groupRoom = new ConcurrentHashMap<>();

    // 用户会话处理
    public static void add(String userId,Session session){
        sessionPool.put(userId,session);
    }

    public static void remove(String userId){
        sessionPool.remove(userId);
    }

    public static List<Session> getSessionsByGid(String gid){
        List<String> uids = groupRoom.get(gid);
        List<Session> list = new CopyOnWriteArrayList<>();
        if(uids!=null){
            uids.parallelStream().forEach(id->{
                list.add(sessionPool.get(id));
            });
        }

        return list;
    }
    // 在线用户数量
    public static int getOnlineCount(String gid){
        return groupRoom.get(gid).size();
    }

    // 用于心跳检测
    public static Collection<Session> getSessions(){
        return sessionPool.values();
    }

    // --------- 群操作 ----------
    public static void addToGroup(String userId,String groupId){
        if(!groupRoom.containsKey(groupId)){
            List<String> list = new ArrayList<>();
            groupRoom.put(groupId,list);
        }
        if(groupRoom.get(groupId).contains(userId)){
            return;
        }
        groupRoom.get(groupId).add(userId);
    }

    public static void leaveGroup(String userId,String groupId){
        if (!groupRoom.containsKey(groupId)) {
            return;
        }
        groupRoom.get(groupId).remove(userId);
        if(groupRoom.get(groupId).isEmpty()){
            groupRoom.remove(groupId);
        }
    }

    public static List<String> getGroupMember(String groupId) {
        return groupRoom.get(groupId);
    }
}
